package com.study.talk.ui.app.login.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.study.talk.R
import com.study.talk.ui.app.base.EventBusBaseFragment
import com.study.talk.ui.app.login.LoginActivity
import com.study.talk.ui.app.register.RegisterActivity
import com.study.talk.databinding.FragmentLoginBinding
import com.study.talk.netty.message.response.LoginResponse
import com.study.talk.ui.app.login.LoginViewModel
import com.study.talk.netty.NettyClient
import com.study.talk.utils.alert.AlertUtil
import com.study.talk.utils.extras.start
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@AndroidEntryPoint
class LoginFragment : EventBusBaseFragment() {

    companion object {
        private const val TAG = "LoginFragment"
    }

    private lateinit var binding: FragmentLoginBinding

    private val loginActivity by lazy { activity as LoginActivity }

    private val parentViewModel by lazy { ViewModelProvider(requireActivity())[LoginViewModel::class] }

    private val vm: LoginFragmentViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false)
        binding.vm = vm
        binding.lifecycleOwner = this

        vm.autoLogin()?.let {
            binding.root.visibility = View.INVISIBLE
            NettyClient.sendMessage(it)
        }

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.loginBt.setOnClickListener {
            if (vm.check()) vm.submit()
        }
        binding.toRegisterBt.setOnClickListener { start(RegisterActivity::class.java) }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessage(response: LoginResponse) {
        Log.i(TAG, "onMessage: ${response.success}")
        if (response.success) {
            parentViewModel.changeResponse(response)
            findNavController().navigate(R.id.action_loginFragment_to_loadingFragment)
        } else {
            AlertUtil.show(loginActivity, "登录失败", response.reason)
            binding.root.visibility = View.VISIBLE
            app.logout()
        }
    }
}